package com.cloud.translation.Fragment;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cloud.translation.Adapter.Language;
import com.cloud.translation.Adapter.HomeAdapter;
import com.cloud.translation.BaseUI.BaseFragment;
import com.cloud.translation.Dao.DaoUtils;
import com.cloud.translation.Model.BaseBean;
import com.cloud.translation.Model.Model;
import com.cloud.translation.R;
import com.cloud.translation.TTS.MyTTS;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HomeFragment extends BaseFragment {

    private TextView language1, language2, message;

    private EditText editText;

    private ImageView play1, play2, delete1, copy, exchange;

    private AppCompatButton button;

    private List<Language> languages;

    private MyTTS myTTS;

    private HomeAdapter adapter1, adapter2;

    private String languageCode, languageCode2;

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        language1 = view.findViewById(R.id.language_1);
        language2 = view.findViewById(R.id.language_2);
        message = view.findViewById(R.id.message);
        editText = view.findViewById(R.id.content);
        play1 = view.findViewById(R.id.content_play);
        play2 = view.findViewById(R.id.message_play);
        delete1 = view.findViewById(R.id.content_delete);
        copy = view.findViewById(R.id.message_copy);
        exchange = view.findViewById(R.id.image_exchange);
        button = view.findViewById(R.id.sure_button);
        myTTS = new MyTTS(getContext());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void setEvent() {
        String[] languageString = getResources().getStringArray(R.array.language);
        languages = new ArrayList<>();
        for (String language : languageString) {
            String[] str = language.split(",");
            Language bm = new Language();
            bm.setName(str[0]);
            bm.setAbbreviations(str[1]);
            languages.add(bm);
        }
        language1.setOnClickListener(l -> {
            OnLanguage(language1, adapter1);
        });
        language2.setOnClickListener(l -> {
            OnLanguage(language2, adapter2);
        });
        exchange.setOnClickListener(l -> {
            String name = language1.getText().toString();
            language1.setText(language2.getText().toString());
            language2.setText(name);
        });
        editText.setHorizontallyScrolling(false);
        editText.setMaxLines(Integer.MAX_VALUE);//设置换行
        editText.setOnEditorActionListener((TextView v, int actionId, KeyEvent event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                getResults();
            }
            return false;
        });
        delete1.setOnClickListener(l -> {
            editText.setText("");
            message.setText("");
        });
        play1.setVisibility(View.GONE);
        play2.setOnClickListener(l -> {
            myTTS.mySpeak(message.getText().toString());
        });
        copy.setOnClickListener(l -> {
            if (!message.getText().toString().equals("")) {
                ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                assert cm != null;
                cm.setPrimaryClip(ClipData.newPlainText(null, message.getText().toString()));
                if (cm.hasPrimaryClip()) {
                    cm.getPrimaryClip().getItemAt(0).getText();
                }
                Snackbar.make(message, "The translation has been saved to the clipboard.", Snackbar.LENGTH_SHORT).show();
            } else {
                Snackbar.make(message, "The translation is empty.", Snackbar.LENGTH_SHORT).show();
            }
        });
        button.setOnClickListener(l -> {
            getResults();
        });
    }

    private void OnLanguage(TextView textView, HomeAdapter adapter) {
        RecyclerView rv = new RecyclerView(getContext());
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        PopupWindow popupWindow = new PopupWindow(rv, textView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
        adapter = new HomeAdapter(getActivity(), textView, popupWindow);
        rv.setAdapter(adapter);
        adapter.setData(languages);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(textView);
    }

    private void getResults() {
        for (Language language : languages) {
            if (language.getName().equals(language1.getText().toString())) {
                languageCode = language.getAbbreviations();
            }
            if (language.getName().equals(language2.getText().toString())) {
                languageCode2 = language.getAbbreviations();
            }
        }
        getTr(languageCode,"ZH_CN",languageCode2,editText.getText().toString());
    }

    private void getTr(String languageCode1,String middle,String languageCode2,String text) {
        Request request = new Request.Builder()
                .url("https://fanyi.youdao.com/translate?&doctype=json&type=" + languageCode1 + "2" + languageCode2 + "&i=" +text )
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.toString();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Snackbar.make(editText, "Save Fail", Snackbar.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                String priceSting = response.body().string();
                try {
                    BaseBean body = gson.fromJson(priceSting, BaseBean.class);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String results = body.getTranslateResult().get(0).get(0).getTgt();
                            if (languageCode2.equals(middle)||languageCode1.equals("ZH_CN")) {
                                message.setText(results);
                                Model bean = new Model();
                                bean.setHistory(editText.getText().toString());
                                bean.setLanguage1(language1.getText().toString());
                                bean.setLanguage2(language2.getText().toString());
                                bean.setResults(results);
                                new DaoUtils(getContext()).insert(bean);
                            }else {
                                getTr(middle,languageCode2,languageCode2,results);
                            }
                        }
                    });
                } catch (Exception e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Snackbar.make(message, "Save Fail", Snackbar.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void getData() {
    }

    @Override
    public void onStop() {
        super.onStop();
        myTTS.stop();
    }

}
